""""
从数据库中写出数据
"""
from logging import exception

from pymysql import Connection
import json
from datetime import date
#构建一个链接对象
conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="123456"
)

#创建一个游标
cursor = conn.cursor()
#链接数据库
conn.select_db("py_sql")
#组织sql语句
sql = f"select * from orders"

cursor.execute(sql)
#拿到查询之后的结果
result: tuple = cursor.fetchall()
with open("D:/mysql_txt","w",encoding='UTF-8') as f:
    #一行一行存入文本文件
    for row in result:
        #每一行的形式都是字典
        order_dict = {}
        #将date类型转化为正常的str类型
        formatted_date = row[0].strftime("%Y-%m-%d")
        order_dict["date"] = formatted_date
        order_dict["order_id"] = row[1]
        order_dict["money"] = row[2]
        order_dict["province"] = row[3]
        #最后转化为json形式写入文件,默认ascii码传入,要设置ensure_ascii=False,不然province:后面会乱码
        line = json.dumps(order_dict,ensure_ascii=False)
        f.write(line)
        f.write("\n")

#执行sql语句

#关闭链接
conn.close()
f.close()
"""
自己进行的尝试

"""

#
# for line in f.readlines():
#         line_tuple = line.split(", ")
#         try:
#             data_dict["date"] += line_tuple[0].strftime("%Y-%m-%d")
#             data_dict["order_id"] +=line_tuple[1]
#             data_dict["money"] += line_tuple[2]
#             data_dict["province"] += line_tuple[3]
#         except exception:
#             data_dict["date"] = line_tuple[0].strftime("%Y-%m-%d")
#             data_dict["order_id"] = line_tuple[1]
#             data_dict["money"] = line_tuple[2]
#             data_dict["province"] = line_tuple[3]
